package com.fuelwallet.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class PriceUtility {
	// Message what
	public static final int MESSAGE_UPDATE_OK = 0;

	private PriceThread pricethread;
	private Thread thread;
	private String output;
	private StringBuilder src;
	private ArrayList<String> fuelnameList;
	private ArrayList<Float> fuelpriceList;
	private ArrayList<FuelPrice> fuelpriceObjectList;
	private boolean lock = false;
	private FuelPriceHandle fuelpricedatabase;
	private Context context;
	private Handler updateHandler;

	public PriceUtility(Context context, Handler updateHandler) {
		this.context = context;
		this.updateHandler = updateHandler;
		src = new StringBuilder();
		output = "";
		pricethread = new PriceThread(src);
		thread = new Thread(pricethread);
		fuelnameList = new ArrayList<String>();
		fuelpriceList = new ArrayList<Float>();
		fuelpriceObjectList = new ArrayList<FuelPrice>();
		fuelpricedatabase = new FuelPriceHandle(context);
	}

	public void startExecution() {
		while (lock)
			;
		lock = true;
		thread.start();
		while (thread.isAlive())
			;
		output = src.toString();
		Log.d("MyApplication", "The output is+" + src.toString());
		lock = false;
		// updateDatabase();
	}

	public void updateDatabase(boolean toast) {
		while (lock)
			;
		lock = true;
		fuelpricedatabase.open();
		for (int i = 0; i < fuelpriceObjectList.size(); i++) {
			FuelPrice fuelpriceTemp = fuelpriceObjectList.get(i);
			ArrayList<String> databaseFuelnameList = (ArrayList<String>) fuelpricedatabase
					.getFuelNameList();
			if (databaseFuelnameList.contains(fuelpriceTemp.getfuelName()))
				fuelpricedatabase.deleteFuelPrice(fuelpriceTemp.getfuelName());
			fuelpricedatabase.putFuelPrice(fuelpriceTemp);
			Log.d("My Application",
					"Fuel Name of " + fuelpriceTemp.getfuelName() + " updated");
		}
		fuelpricedatabase.close();
		lock = false;
		if (toast) {
			Toast.makeText(context,
					"Fuel Price Updated, click Price List to view",
					Toast.LENGTH_LONG).show();
		}
		
		updateHandler.obtainMessage(MESSAGE_UPDATE_OK).sendToTarget();
	}

	public void analyze() {
		if (thread.isAlive())
			;
		fuelpriceList = new ArrayList<Float>();
		fuelnameList = new ArrayList<String>();

		Scanner scanner = new Scanner(output);
		scanner.useDelimiter("<td class=oil>");
		scanner.next();
		String temp = null;
		while (scanner.hasNext()) {
			scanner.next();
			if (!scanner.hasNext())
				break;
			temp = scanner.next();
			if (temp.contains("<b>")) {
				Scanner namescanner = new Scanner(temp);
				namescanner.useDelimiter("<b>|</b>");
				namescanner.next();
				String fuelnametemp = namescanner.next();
				fuelnametemp = fuelnametemp.replace("</a> ", " ");
				fuelnametemp = fuelnametemp.replace(";", "").trim();
				Log.d("MyApplication", "Name of the fuel:" + fuelnametemp);
				fuelnameList.add(fuelnametemp);
			} else {
				Scanner pricescanner = new Scanner(temp);
				pricescanner.useDelimiter("</td>");
				String fuelpricetemp = pricescanner.next();
				fuelpricetemp = fuelpricetemp.substring(1).trim();
				Log.d("MyApplication", "Price of the fuel:" + fuelpricetemp);
				fuelpriceList.add(Float.valueOf(fuelpricetemp));
			}
		}
		for (int i = 0; i < fuelnameList.size(); i++) {
			fuelpriceObjectList.add(new FuelPrice((String) fuelnameList.get(i),
					(Float) fuelpriceList.get(i)));    					// possible errors here-------------------------------------
		}

	}

	public ArrayList<FuelPrice>  getFuelPriceInList() {
		while (lock)
			;
		lock = true;
		if (fuelnameList.size() != fuelpriceList.size()
				|| fuelnameList.size() == 0)
			return null;
		lock = false;
		return fuelpriceObjectList;
	}

	class PriceThread implements Runnable {
		private String url;
		private HttpClient client;
		private HttpGet request;
		private HttpResponse response;
		private StringBuilder str;

		public PriceThread(StringBuilder src) {
			url = "http://www.consumer.org.hk/pricewatch/oilwatch/eng/graph.php?action=volume&volume=1&amount=&grade=all&filtercompany=&cri%5B%5D=cash&show=all&filtercreditcard=&userebatepoint=&usebonus=0&usebonuspoint=&week=0#result";
			client = new DefaultHttpClient();
			request = new HttpGet(url);
			this.str = src;
		}

		public void run() {
			try {
				Log.d("MyActivity", "What the fuck");
				response = client.execute(request);
				InputStream in = response.getEntity().getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));
				String line = null;
				while ((line = reader.readLine()) != null) {
					str.append(line);
					// Log.d("MyActivity",line);
				}
				in.close();
				// Log.d("MyApplication","The output is+"+src.toString());
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

}
